package playn101.core;

import static playn.core.PlayN.*;
import java.util.ArrayList;

import playn.core.Game;
import playn.core.Image;
import playn.core.ImageLayer;
import playn.core.GroupLayer;
import playn.core.Pointer;
import playn.core.Canvas;
import playn.core.CanvasImage;

public class D implements Game {
  CanvasImage bgImage;
  ImageLayer bgLayer;
  Image cloudImage;
  ImageLayer cloudLayer;
  float x;
  float y;
  Image ballImage;
  GroupLayer ballLayer;

  class Ball {
    public ImageLayer layer;
    float angle = 0.0f;
    public Ball(Image image, float x, float y) {
      layer = graphics().createImageLayer(image);
      layer.setOrigin(ballImage.width() / 2f, ballImage.height() / 2f);
      layer.setTranslation(x, y);
    }
    public void update(float delta) {
      layer.setRotation(angle);
      angle += delta;
    }
  }
  ArrayList<Ball> balls = new ArrayList<Ball>();

  @Override
  public void init() {
    bgImage = graphics().createImage(800, 600);
    Canvas canvas = bgImage.canvas();
    canvas.setFillColor(0xff87ceeb);
    canvas.fillRect(0, 0, 800, 600);
    bgLayer = graphics().createImageLayer(bgImage);
    graphics().rootLayer().add(bgLayer);
    cloudImage = assetManager().getImage("images/cloud.png");
    cloudLayer = graphics().createImageLayer(cloudImage);
    graphics().rootLayer().add(cloudLayer);
    x = 24.0f;
    y = 3.0f;

    ballImage = assetManager().getImage("images/ball.png");
    ballLayer = graphics().createGroupLayer();
    graphics().rootLayer().add(ballLayer);
    pointer().setListener(new Pointer.Adapter() {
      @Override
      public void onPointerEnd(Pointer.Event event) {
	Ball ball = new Ball(ballImage, event.x(), event.y());
	balls.add(ball);
	ballLayer.add(ball.layer);
      }
    });
  }

  @Override
  public void paint(float alpha) {
    // the background automatically paints itself, so no need to do anything here!
  }

  @Override
  public void update(float delta) {
    cloudLayer.setTranslation(x, y);
    x += 0.1f * delta;
    if (x > bgImage.width() + cloudImage.width()) {
      x = -cloudImage.width();
    }
    for (Ball ball : balls) {
      ball.update(delta);
    }
  }

  @Override
  public int updateRate() {
    return 25;
  }
}
